package com.sense.lib.webview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.sense.lib.webview.callback.OnUrlListener;


@SuppressLint("SetJavaScriptEnabled")
public class SenseWebView extends WebView  {

    private final String TAG = "SenseWebView";
    public SenseWebViewClient mClient;

    public SenseWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SenseWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public SenseWebView(Context context) {
        super(context);
        init();
    }

    private void init() {
        this.setVerticalScrollBarEnabled(false);
        this.setHorizontalScrollBarEnabled(false);
        this.getSettings().setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        setWebViewClient(generateBridgeWebViewClient());
    }

    @Override
    public void setWebViewClient(WebViewClient client) {
        if (client instanceof SenseWebViewClient) {
            mClient = (SenseWebViewClient) client;
            super.setWebViewClient(client);
        }
    }

    public SenseWebViewClient getBridgeWebViewClient() {
        return mClient;
    }

    protected SenseWebViewClient generateBridgeWebViewClient() {
        return new SenseWebViewClient(this);
    }
    public void setOnUrlListener(OnUrlListener mUrlListener) {
        if (mClient!=null){
            mClient.setOnUrlListener(mUrlListener);
        }

    }
    /**
     * <br> Description: 清空数据
     * <br> Author:      lionszhang
     * <br> Date:        2017/11/3 13:59
     */
    @Override
    public void destroy() {
        if (mClient != null) {
            mClient.destroy();
        }
        if (getParent() != null) {
            ((ViewGroup) getParent()).removeView(this);
        }
        super.destroy();
    }
}
